/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.audit.aop  
 */
package com.apache.client;

import java.util.Map;

import org.apache.log4j.Logger;

import com.apache.attachment.mommon.ToolsUtil;
import com.apache.method.SystemRunnable;
import com.apache.rpc.client.RpcProtoclClient;
import com.apache.rpc.entity.InterfaceRegister;

/**
 * description:  日志添加线程
 * @author Hou Dayu 创建时间：2014-8-8  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
public class LoggerClientRunnable extends SystemRunnable {

	private Logger log = Logger.getLogger(LoggerClientRunnable.class);
	private Object obj;
	private Map<String, Object> logMap;

	public LoggerClientRunnable(Object obj, Map<String, Object> logMap) {
		this.obj = obj;
		this.logMap = logMap;
	}

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see java.lang.Runnable#run()  
	 */
	public void run() {
		try {
			String mark = "false";
			String returnValue = String.valueOf(logMap.get("log_returnValue"));
			if ("save".equals(logMap.get("logType"))) {
				if (!isNull(returnValue)) {
					mark = "true";
				}
			} else if ("edit".equals(logMap.get("logType")) || "delete".equals(logMap.get("logType"))) {
				if (!isNull(returnValue)) {
					mark = returnValue;
				}
			} else {
				mark = returnValue;
			}
			if (!"true".equals(mark))
				return;
			if (null != obj) {
				Map beanInfo = StringUtil.convertBean(obj);
				logMap.putAll(beanInfo);
			}
			InterfaceRegister register = getInterfaceRegister();
			if (isNull(register.getAddress()) || isNull(register.getCallType())) {
				RpcProtoclClient.getInstance().doService("auditService", "logOperationSave", logMap);
			} else {
				RpcProtoclClient.getInstance().doService("auditService", "logOperationSave", logMap, register);
			}
		} catch (Throwable e) {
			log.error(e);
		}
	}

	private InterfaceRegister getInterfaceRegister() {
		InterfaceRegister register = new InterfaceRegister();
		String type = ToolsUtil.getInstance().getValueByKey("audit_server_type");
		register.setCallType(type);
		String address = ToolsUtil.getInstance().getValueByKey("audit_server_url");
		if ("socket".equals(type)) {
			register.setAddress(address);
			register.setPort(ToolsUtil.getInstance().getValueByKey("audit_server_port"));
		} else {
			String url = address + "/audit/service/doService.action";
			register.setAddress(url);
		}
		return register;
	}

	/**
	 *判断对象数组是否为空
	 * 
	 * @param  object 对象数组
	 * @return        如果object为空返回true，不为空返回false 
	 */
	private boolean isNull(String str) {
		if (str == null) {
			return true;
		}
		str = str.trim();
		if ((str.equalsIgnoreCase("null")) || (str.equals(""))) {
			return true;
		}
		return false;
	}
}
